package pack;

import java.util.HashMap;
import java.util.Date;

interface Http {
	String execute(StringBuilder request);
}

public class Interpreter {

	/*
	 * Structure of an HTTP request:
	 * 
	 * COMMAND /ADDRESS HTTP-VERSION Header: data
	 * 
	 * Example: GET / HTTP/1.1
	 */

	static Date today = new Date();

	static String header = "HTTP/1.1 200 OK\n" + "Date: %s\n"
			+ "Server: Absaber/0.1 (Unix) (Fedora/Linux)\n"
			+ "Content-Type: text/html; charset=UTF-8\n"
			+ "Content-Length: %d\n" + "Connection: close\n";

	static String response_model = "%s\n" + "<html><head>\n"
			+ "<title>An Example Page</title>\n"
			+ "<script> console.log('------');</script>" + "</head><body>\n"
			+ "Hello World, this is a very simple HTML document.\n" + "%s"
			+ "</body></html>";

	private static HashMap<String, Http> interpreter = new HashMap<String, Http>();

	// @ requires http_request != null;
	// @ ensures \response != null;
	public static String understand(StringBuilder http_request) {

		interpreter.put("GET", new Http() {
			public String execute(StringBuilder request) {
				String mac = request.toString().split(" ")[1].replace("/", "");
				System.out.println(mac);
				String response = String.format(response_model, String.format(
						header, today.toString(), response_model.length()
								+ header.length() + 200), "AP: "
						+ Network.getInstance().search(mac));
				return response;
			}
		});

		interpreter.put("get", new Http() {
			public String execute(StringBuilder request) {
				String mac = request.toString().split(" ")[1].replace("/", "");
				System.out.println(mac);
				String response = String.format(response_model, String.format(
						header, today.toString(), response_model.length()
								+ header.length() + 200), "AP: "
						+ Network.getInstance().search(mac)
						+ "\n<h1>HEHEHEEH</h1>");
				return response;
			}
		});

		interpreter.put("HEAD", new Http() {
			public String execute(StringBuilder http_request) {
				System.out.println("HEAD request");
				return String.format(header + "\n It was a HEAD request",
						today.toString(),
						(header + today.toString()).length() + 100);
			}
		});

		String[] raw = http_request.toString().split(" ");

		System.out.println(raw[0]);
		if (interpreter.containsKey(raw[0])) {
			interpreter.get(raw[0]).execute(http_request);
		} else {
			return String.format(response_model, today.toString(), today
					.toString().length() + response_model.length() + 200,
					"Invalid request");
		}

		return "";
	}
}